import { Status } from '@/models/sys'
import { defineStore } from 'pinia'
import { ref } from 'vue'

const initState = {
  nickname: '',
  avatar: '',
  token: '',
  isWxSuccess: Status.No,
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...initState })

    const appId = ref<string>('')

    /** 应用id */
    function setAppId(val: string) {
      appId.value = val
    }

    /** 应用id获取 */
    function getAppId() {
      return appId.value
    }

    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }

    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }

    const setToken = (token: string) => {
      userInfo.value.token = token
    }

    const setWxUserStatus = (val: Status) => {
      userInfo.value.isWxSuccess = val
    }

    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }
    const isLogined = computed(
      () => !!userInfo.value.token && userInfo.value.isWxSuccess === Status.Yes,
    )

    return {
      appId,
      userInfo,
      setUserInfo,
      clearUserInfo,
      isLogined,
      reset,
      setToken,
      setWxUserStatus,
      setAppId,
      getAppId,
    }
  },
  {
    persist: true,
  },
)
